package com.demo14;

import java.util.HashMap;
import java.util.Set;
import java.util.TreeMap;

public class StringUtil {

    //计算字符串中每个字符出现的次数
    public static String CharacterComputed(String string){
        //判断内容是否为空
        if(string.length()<=0){
            return "";
        }

        //定义一个hashMap集合，存储数据
//        HashMap<Character, Integer> hashMap = new HashMap<>();
        TreeMap<Character, Integer> hashMap = new TreeMap<Character,Integer>();

        //循环字符串，然后判断是否存在某个字符
        for (int i =0;i<string.length();i++){
            //拿到字符串中循环的字符
            char c = string.charAt(i);
            //hashMap中获取当前字符串看是否存在
            Integer val = hashMap.get(c);
            if(val == null){//第一次直接追加
                hashMap.put(c,1);
            }else{
                val++;//自动拆箱了
                hashMap.put(c,val);
            }
        }

        StringBuilder strBuilder = new StringBuilder();
        //循环找到的字符串内容并进行数据组装遍历循环map
        Set<Character> characters = hashMap.keySet();
        for (Character chr: characters){
            //获取循环的次数的内容
            Integer value = hashMap.get(chr);
            //动态字符串拼接操作
            strBuilder.append(chr).append("(").append(value).append(")");
        }

        return strBuilder.toString();
    }
}
